﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;

public partial class Form_AddToGioHang : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["MaSP"] != null)
        {
            int maSp =(int)int.Parse(Request.QueryString["MaSP"].ToString());
            string tenSP = Request.QueryString["TenSP"].ToString();
            int donGia = (int)int.Parse(Request.QueryString["DonGia"].ToString());
            string linkHinh = Request.QueryString["LinkHinh"].ToString();
            AddNewCart(maSp, tenSP, donGia, linkHinh, 1);
            Response.Redirect("GioHang.aspx");
        }
    }

    public void AddNewCart(int maSp,string tenSP,int dongia, string linkHinh, int soLuong)
    {
        List<NewCart>  listNewCart =(List<NewCart>)Session["Cart"];
        var res = from s in listNewCart
                  where s.MaSp == maSp
                  select s;
        NewCart nC = new NewCart();
        if (listNewCart.Count > 0)
        {
            if (res.FirstOrDefault() != null)
            {
                NewCart newC = new NewCart();
                newC = res.FirstOrDefault();
                nC.MaSp = newC.MaSp;
                nC.HinhAnh = newC.HinhAnh;
                nC.Gia = newC.Gia;
                nC.SoLuong = newC.SoLuong + soLuong;
                nC.TenSP = tenSP;
                nC.TongTien = newC.SoLuong * newC.Gia;
                listNewCart.Remove(newC);

            }
            else
            {
                nC.MaSp = maSp;
                nC.HinhAnh = linkHinh;
                nC.Gia = dongia;
                nC.SoLuong = soLuong;
                nC.TenSP = tenSP;
                nC.TongTien = nC.SoLuong * nC.Gia;
            }
        }
        else
        {
            listNewCart = new List<NewCart>();
            nC.MaSp = maSp;
            nC.HinhAnh = linkHinh;
            nC.Gia = dongia;
            nC.SoLuong = soLuong;
            nC.TenSP = tenSP;
            nC.TongTien = nC.SoLuong * nC.Gia;
        }
        listNewCart.Add(nC);
        Session["Cart"] = listNewCart;
    }
}